/*
 * @Author: wjc
 * @Date: 2025-07-30 16:04:23
 * @LastEditors: wjc
 * @LastEditTime: 2025-09-19 14:33:53
 * @Description:
 */
import type { App } from 'vue'
import type { RouteRecordName, RouteRecordRaw } from 'vue-router'

import { createRouter, createWebHistory } from 'vue-router'

import { createRouterGuard } from './guard'
import { routes } from './routes'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  scrollBehavior: () => ({ left: 0, top: 0 }),
  routes,
})

function getConstRouterName(constRouter: RouteRecordRaw[], list: RouteRecordName[]) {
  constRouter.forEach((item) => {
    if (item.name) {
      list.push(item.name)
    }
    if (item.children) {
      getConstRouterName(item.children, list)
    }
  })
}

/**
 * 路由重置
 */
export function resetRouter() {
  const constRouterName: any[] = []
  getConstRouterName([], constRouterName)
  // 遍历路由并移除
  router.getRoutes().forEach((route) => {
    const { name } = route
    // 常量路由不重置
    if (name && !constRouterName.includes(name)) {
      router.hasRoute(name) && router.removeRoute(name)
    }
  })
}

/**
 * 启动路由
 * @param app 应用实例
 */
export function setupRouter(app: App<Element>) {
  app.use(router)
  createRouterGuard(router)
}

export { router }
